package com.compassoft.webapp.action;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginAction {
	private String username;
	private String password;
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	private static final transient Logger log = LoggerFactory
			.getLogger(LoginAction.class);

	private org.apache.shiro.web.mgt.DefaultWebSecurityManager securityManager;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login() throws Exception {
		return SUCCESS;
	}

	public String execute() throws Exception {
		log.info("此处打log");
		if (isAllow(getUsername(), getPassword())) {
			return SUCCESS;
		}
		return ERROR;
	}

	public boolean isAllow(String name, String password) {

		// 获取当前用户
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		try {
			// 验证是否登录成功
			user.login(token);
		} catch (UnknownAccountException uae) {
			// 用户名不存在
			System.out.println("There is no user with username of "
					+ token.getPrincipal());
			return false;
		} catch (IncorrectCredentialsException ice) {
			// 用户名对应的密码错误
			System.out.println(token.getPrincipal() + " 的密码是错误的!");
			return false;
		} catch (LockedAccountException lae) {
			// 登录用户被锁定，登录失败
			System.out.println("The account for username "
					+ token.getPrincipal() + " is locked.  "
					+ "Please contact your administrator to unlock it.");
			return false;
		} catch (AuthenticationException ae) {
			ae.printStackTrace();
			System.out.println("登录失败");
			return false;
		}

		// 角色检查(管理者or普通用户)
		if (user.isAuthenticated()) {
//			if (user.hasRole("admin")) {
//				System.out.println("May the Admin be with you!");
//			} else {
//				System.out.println("May the member be with you!");
//			}
			return true;
		}
		//
		return true;
	}

	public org.apache.shiro.web.mgt.DefaultWebSecurityManager getSecurityManager() {
		return securityManager;
	}

	public void setSecurityManager(
			org.apache.shiro.web.mgt.DefaultWebSecurityManager securityManager) {
		this.securityManager = securityManager;
	}

}
